package linlist;
//Einfach verkettete Lineare Liste ohne Knoten
public class LinearList{
  protected Object data;
  protected LinearList rest;

  protected LinearList(Object obj){
    data=obj;
  }

  public LinearList(){this(null);}

  protected LinearList forward(int i){
    LinearList wander=this;
    while(wander.rest!=null && --i>=0)
      wander=wander.rest;
    return wander;
  }

  public boolean isempty(){return rest==null;}

  public int length(){
    int len=0;
    LinearList wander=this;
    while(wander.rest!=null){
      wander=wander.rest;
      len++;
    }
    return len;
  }

  public Object get(int weiter){
    LinearList vor=forward(weiter);
    if(vor.isempty()) return null;
    else return vor.rest.data;
  }

  public void insert(Object obj, int weiter){
    LinearList neu=new LinearList(obj);
    LinearList vor=forward(weiter);
    neu.rest=vor.rest;
    vor.rest=neu;
  }

  public Object delete(int weiter){
    LinearList vor=forward(weiter);
    if(vor.isempty()) return null;
    Object obj=vor.rest.data;
    vor.rest=vor.rest.rest;
    return obj;
  }

  public int indexOf(Object obj, int start){
    LinearList wander=this;
    for(int i=0; i<start; i++){
      if(wander.rest==null) return -1;
      wander=wander.rest;
    }
    while(wander.rest!=null){
      wander=wander.rest;
      if(wander.data==obj) return start;
      start++;
    }
    return -1;
  }

  public boolean equals(Object obj){
    if(!(obj instanceof LinearList)) return false;
    LinearList ll=(LinearList)obj;
    LinearList wander=this;
    while(wander.rest!=null){
      if(ll.rest==null) return false;
      wander=wander.rest;
      ll=ll.rest;
      if(!wander.data.equals(ll.data)) return false;
    }
    return ll.rest==null;
  }

  public String toString(){
    LinearList wander=this;
    StringBuffer sb=new StringBuffer();
    while(wander.rest!=null){
      wander=wander.rest;
      sb.append(wander.data);
      sb.append(" ");
    }
    return sb.toString();
  }
}
